from flask import request, redirect, url_for, flash, render_template, jsonify, current_app
from app.main.forms import TypeForm, AddTelForm
from app.main.mail import send_mail
from app.models import UserInfo, TypeTel, TelBook
from . import main
from app import db
from flask_login import login_required, current_user


from app.log_info import Logging


@main.before_app_first_request
def init_request():
    Logging(request, "客户端第一次访问开始访问页面").info_log()


@main.before_app_request
def request_page():
    Logging(request, "访问页面").info_log()


# @main.teardown_app_request
# def teardown_page(e):
#     if e:
#         option_log("异常：%s" % e)


# 首页
@main.route('/index/')
def index():
    tel_book_list = current_user.telbooks
    type_list = TypeTel.query.all()
    return render_template("main/index.html", tel_book_list=tel_book_list, type_list=type_list)


# 添加联系人类型
@main.route('/type/', methods=["GET", "POST"])
@login_required
def tel_type():
    form = TypeForm()
    if form.validate_on_submit():
        type_tel = TypeTel(name=form.name.data)
        db.session.add(type_tel)
        try:
            db.session.commit()
            return redirect(url_for("main.index"))
        except Exception as e:
            db.session.rollback()
            flash("类别已存在")
    return render_template('main/type.html', form=form)


# 添加联系人
@main.route('/add_tel/', methods=["GET", "POST"])
@login_required
def add_del():
    form = AddTelForm()
    if form.validate_on_submit():
        id = current_user.id
        tel_book = TelBook(name=form.name.data, tel=form.tel.data, user_id=id,
                           typetel_id=form.typetel_id.data)
        db.session.add(tel_book)
        try:
            db.session.commit()
            return redirect(url_for("main.index"))
        except Exception as e:
            db.session.rollback()
            flash("异常，请重试")
    return render_template("main/add_tel.html", form=form)


# 修改联系人
@main.route('/update_tel/', methods=['GET', 'POST'])
@login_required
def update_tel():
    id = request.values["id"]
    tel_book = TelBook.query.filter_by(id=id)[0]
    form = AddTelForm(obj=tel_book)
    if form.validate_on_submit():
        tel_book.name = form.name.data
        tel_book.tel = form.tel.data
        tel_book.typetel_id = form.typetel_id.data
        db.session.add(tel_book)
        try:
            db.session.commit()
            return redirect(url_for("main.index"))
        except Exception as e:
            db.session.rollback()
            flash("好像出了问题~~")
    return render_template("main/add_tel.html", form=form)


# 删除
@main.route('/del_tel/', methods=['GET'])
@login_required
def del_tel():
    id = request.values["id"]
    tel_book = TelBook.query.filter_by(id=id)[0]
    db.session.delete(tel_book)
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
    return redirect(url_for("main.index"))


# 条件查询，ajax调用
@main.route('/ajax/sel_text/')
@login_required
def sel_text():
    name_text = request.values["text"]
    tel_list = TelBook.query.filter(TelBook.name.contains(name_text)).all()
    list_str = []
    for item in tel_list:
        type_name = item.typetels.name
        dic = item.__dict__
        dic["type_name"] = type_name
        dic.__delitem__('_sa_instance_state')
        dic.__delitem__('typetels')
        list_str.append(dic)
    return jsonify(list_str)


# 分类查询
@main.route('/sel_type/')
@login_required
def sel_type():
    type_id = request.values["type_id"]
    tel_list = None
    if type_id == '0':
        tel_list = TelBook.query.all()
    else:
        tel_list = TelBook.query.filter_by(typetel_id=type_id).all()
    list_str = []
    for item in tel_list:
        type_name = item.typetels.name
        dic = item.__dict__
        dic["type_name"] = type_name
        dic.__delitem__('_sa_instance_state')
        dic.__delitem__('typetels')
        list_str.append(dic)
    return jsonify(list_str)
